/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-20 15:41:55
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-08-05 17:50:56
 * @FilePath: \vite-project\src\utils\helper.ts
 */
import { UploadFile } from 'antd';
import axios from 'axios';
import { confirmAuthFileUploadUrl, getAuthFileUploadUrl } from 'apis/common';

export function findLeafNodes(node: any) {
    if (!node?.children || node?.children?.length === 0) {
        // 如果节点没有子节点，它是叶子节点
        return [node];
    }
    // 对每个子节点递归调用
    return node?.children?.flatMap(findLeafNodes);
}

/**
 * 获取文件名
 * @param fileName
 * @returns
 */
export const getFileType = (fileName: string) => {
    const queryIndex = fileName.lastIndexOf('?');
    queryIndex >= 0 && (fileName = fileName.substring(0, queryIndex).toLowerCase());
    const startIndex = fileName.lastIndexOf('.');
    if (startIndex != -1) return fileName.substring(startIndex + 1, fileName.length).toLowerCase();
    return '';
};

export const getImageAndFileType = (fileName: string) => {
    let type = getFileType(fileName);
    if (['jpg', 'png', 'webp'].includes(type)) {
        type = 'images';
    }

    return type;
};

export const Uploder: (file: UploadFile) => Promise<{
    authQueryFileUrl: string;
    attachId: string;
    filePath: string;
}> = (file: UploadFile, sysFileTag: 1 | 2) =>
    new Promise(async (resolve, reject) => {
        try {
            const { authPutUrl, attachId, filePath } = await getAuthFileUploadUrl({
                fileName: file.name,
                type: getFileType(file.name || ''),
                sysFileTag,
            });
            const url = authPutUrl;
            const { status } = await axios.put(url, file, {
                headers: {
                    'Content-Type': '',
                },
            });
            if (status === 200) {
                const { authQueryFileUrl } = await confirmAuthFileUploadUrl({
                    attachId,
                });
                resolve({
                    authQueryFileUrl,
                    attachId,
                    filePath,
                });
            } else {
                reject(status);
            }
        } catch (error) {
            console.error(error);
            reject(error);
        }
    });

/**
 * 校验身份证
 * @param rule
 * @param value
 * @returns
 */
export const validateIdCard = (rule: any, value: string) => {
    if (!value) {
        return Promise.resolve();
    }
    if (/^([0-9]){7,18}(x|X)?$/.test(value) || /^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$/.test(value)) {
        return Promise.resolve();
    }
    return Promise.reject(new Error('请输入正确的身份证号码'));
};

/**
 * 校验手机号
 * @param rule
 * @param value
 * @returns
 */
export const validateMobile = (rule: any, value: string) => {
    if (!value || /1[3-9]\d{9}/.test(value)) {
        return Promise.resolve();
    }
    return Promise.reject(new Error('请输入正确的手机号码！'));
};

/**
 * 校验文本
 * @param rule
 * @param value
 * @returns
 */
export const validateText = (rule: any, value: string, { api }) => {
    if (api && value) {
        return new Promise((resolve, reject) => {
            api()
                ?.then((res) => {
                    if (/^[\u4E00-\u9FA5A-Za-z0-9]+$/.test(value)) {
                        resolve(true);
                    } else {
                        reject(new Error('只允许填写中文、字母、数字'));
                    }
                })
                .catch((error) => {
                    reject(new Error(error?.rspDesc || '校验失败'));
                });
        });
    }
    if (!value || /^[\u4E00-\u9FA5A-Za-z0-9]+$/.test(value)) {
        return Promise.resolve();
    }
    return Promise.reject(new Error('只允许填写中文、字母、数字'));
};

/**
 * 排序
 * @param calculateRules
 * @returns
 */
export const sortCarSpecRulesByType = (calculateRules?: any[]) => {
    const list = JSON.parse(JSON.stringify(calculateRules));
    const rulesMap: {
        [x: number]: any[];
    } = {};
    const ruleList = [];
    list?.map((item, index) => {
        if (rulesMap?.[item.type]?.length) {
            rulesMap[item.type].push(item);
        } else {
            rulesMap[item.type] = [item];
        }
    });
    for (const k in rulesMap) {
        ruleList.push(rulesMap[k]);
    }
    console.log('-----rulesMap---', rulesMap);
    return JSON.parse(JSON.stringify(ruleList));
};

// 将字符串复制到剪切板
export function copyToClipboard(text: string) {
    return (message) => {
        // 首先检查Clipboard API是否可用
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard
                .writeText(text)
                .then(() => {
                    message.success('复制成功');
                    console.log('Text copied to clipboard successfully.');
                })
                .catch((err) => {
                    message.error('复制失败');
                    console.error('Failed to copy text to clipboard.', err);
                });
        } else {
            // Clipboard API不可用，尝试使用document.execCommand
            // 创建一个临时的textarea元素来选中文本，以便复制
            const textarea = document.createElement('textarea');
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            try {
                // 执行复制操作
                const successful = document.execCommand('copy');
                const msg = successful ? 'successful' : 'unsuccessful';
                message.success('复制成功');
            } catch (err) {
                message.error('复制失败');
            }
            // 清理临时创建的textarea
            document.body.removeChild(textarea);
        }
    };
}

/**
 * 数组拆分
 * @param arr
 * @param size
 * @returns
 */
export const splitArray = (arr: any[], size: number) => {
    const result = [];
    for (let i = 0; i < arr.length; i += size) {
        result.push(arr.slice(i, i + size));
    }
    return result;
};

/**
 * 数组对象根据key进行分组
 * @param array
 * @param key
 * @returns
 */
export const groupBy = (array, key) =>
    array.reduce((result, currentItem) => {
        // 使用 key 的值作为分组的键
        const groupKey = currentItem[key];

        // 如果 result 中不存在这个键，则创建一个数组
        if (!result[groupKey]) {
            result[groupKey] = [];
        }

        // 将当前项推入对应的分组数组中
        result[groupKey].push(currentItem);

        return result;
    }, {});
